package com.liangfeng.breezebrowser.browsermvp.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.liangfeng.breezebrowser.EditTextChangeListener;
import com.liangfeng.breezebrowser.KeyWordEvent;
import com.liangfeng.breezebrowser.R;
import com.liangfeng.breezebrowser.base.BaseActivity;
import com.liangfeng.breezebrowser.base.BrowserApplication;
import com.liangfeng.breezebrowser.base.Contants;
import com.liangfeng.breezebrowser.bean.BookMarkBean;
import com.liangfeng.breezebrowser.bean.BrowHistoryBean;
import com.liangfeng.breezebrowser.bean.KeyWordBean;
import com.liangfeng.breezebrowser.bean.WindowBean;
import com.liangfeng.breezebrowser.browsermvp.BrowserPresenter;
import com.liangfeng.breezebrowser.browsermvp.view.webview.BrowserChromeClient;
import com.liangfeng.breezebrowser.browsermvp.view.webview.BrowserClient;
import com.liangfeng.breezebrowser.utils.ToastUtil;
import com.liulishuo.magicprogresswidget.MagicProgressBar;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Types.BoomType;
import com.nightonke.boommenu.Types.ButtonType;
import com.nightonke.boommenu.Types.PlaceType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by mozhifeng on 2017/5/24.
 */

public class BrowserActivity extends BaseActivity implements View.OnClickListener, View.OnFocusChangeListener, IBrowserView, AdapterView.OnItemClickListener {


    /**
     * Presenter与view产生联系
     */
    private BrowserPresenter browserPresenter = new BrowserPresenter(this);
    private ListView lvKeyWords;
    private List<String> keyWordList;

    private boolean flag = false;
    private Realm realm;
    private final String HOME_URL = "http://www.baidu.com/";
    private MagicProgressBar mpb;
    private BoomMenuButton boomMenuButton;
    private List<WindowBean> bitmaps;
    private List<WebView> windows = new ArrayList<>();
    private RelativeLayout rlWebGroup;
    private LinearLayout llWindowsOperater;

    private final String LINEARlAYOUT = "LINEARlAYOUT";
    private final String LISTVIEW = "LISTVIEW";
    private final String RELATIVELAYOUT = "RELATIVELAYOUT";
    //    private WebView newWebView;
    private Bitmap drawingCache;
    private QuickAdapter quickAdapter;
    private int webViewCount = 1;
    private RelativeLayout.LayoutParams layoutParams;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //register EventBus
        EventBus.getDefault().register(this);
        //get the Realm instance.
        realm = Realm.getDefaultInstance();
        bitmaps = new ArrayList<>();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Close the Realm instance.
        realm.close();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            ivGo.setVisibility(View.VISIBLE);
            boomMenuButton.setVisibility(View.GONE);
        } else {//lose focus
            ivGo.setVisibility(View.GONE);
            boomMenuButton.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBackPressed() {//与onKeyDown配合使用
        //其中webView.canGoBack()在webView含有一个可后退的浏览记录时返回true
        LogUtils.e("onBackPressed");
        if (mCurrentView.canGoBack()) {
            mCurrentView.goBack();
        } else {
            clearFocus(etUrl);
            closeKeyboard(etUrl, this);
        }
        if (isVISIBLE(lvBookMarks, LISTVIEW)) {
            lvBookMarks.setVisibility(View.GONE);
        }
        if (isVISIBLE(lvHistory, LISTVIEW)) {
            lvBookMarks.setVisibility(View.GONE);
        }
        if (isVISIBLE(llWindowsOperater, LINEARlAYOUT)) {
            switchover1();
            rvWindows.setVisibility(View.GONE);
        }

        super.onBackPressed();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //其中webView.canGoBack()在webView含有一个可后退的浏览记录时返回true
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mCurrentView.canGoBack()) {
            mCurrentView.goBack();
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && isVISIBLE(lvHistory, LISTVIEW)) {
            lvHistory.setVisibility(View.GONE);
            return false;//不走父类的方法
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && isVISIBLE(lvBookMarks, LISTVIEW)) {
            lvBookMarks.setVisibility(View.GONE);
            return false;//不走父类的方法
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && isVISIBLE(llWindowsOperater, LINEARlAYOUT)) {
            switchover1();
            rvWindows.setVisibility(View.GONE);
            return false;//不走父类的方法
        }

        return super.onKeyDown(keyCode, event);
    }

    public boolean isVISIBLE(View view, String flag) {
        switch (flag) {
            case LISTVIEW:
                ListView listView = (ListView) view;
                return isVisible(listView.getVisibility());
            case RELATIVELAYOUT:
                RelativeLayout relativeLayout = (RelativeLayout) view;
                return isVisible(relativeLayout.getVisibility());
            case LINEARlAYOUT:
                LinearLayout linearLayout = (LinearLayout) view;
                return isVisible(linearLayout.getVisibility());

        }
        return false;
    }

    private boolean isVisible(int visibility) {
        if (visibility == View.VISIBLE) {
            return true;
        }
        return false;
    }

    @Override
    public void initData() {
        loadHomePage();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        ColorDrawable drawable = new ColorDrawable(0xffff0000);
        boomMenuButton.init(
                Contants.drawables, // 子按钮的图标Drawable数组，不可以为null
                Contants.texts,     // 子按钮的文本String数组，可以为null
                Contants.colors,    // 子按钮的背景颜色color二维数组，包括按下和正常状态的颜色，不可为null
                ButtonType.HAM,     // 子按钮的类型
                BoomType.PARABOLA,  // 爆炸类型
                PlaceType.HAM_3_1,  // 排列类型
                null,               // 展开时子按钮移动的缓动函数类型
                null,               // 展开时子按钮放大的缓动函数类型
                null,               // 展开时子按钮旋转的缓动函数类型
                null,               // 隐藏时子按钮移动的缓动函数类型
                null,               // 隐藏时子按钮缩小的缓动函数类型
                null,               // 隐藏时子按钮旋转的缓动函数类型
                null                // 旋转角度
        );

        boomMenuButton.setOnSubButtonClickListener(new BoomMenuButton.OnSubButtonClickListener() {
            @Override
            public void onClick(int buttonIndex) {
                LogUtils.e(buttonIndex);
                switch (buttonIndex) {
                    case 0://Book Mark
                        RealmResults<BookMarkBean> bookMarks = realm.where(BookMarkBean.class).findAll();
                        lvBookMarks.setVisibility(View.VISIBLE);
                        lvBookMarks.setAdapter(new BookMarkAdapter(bookMarks, BrowserApplication.context));
                        break;
                    case 1://Browser History
                        RealmResults<BrowHistoryBean> historys = realm.where(BrowHistoryBean.class).findAll();
                        lvHistory.setVisibility(View.VISIBLE);
                        lvHistory.setAdapter(new BrowserHistoryAdapter(historys, BrowserApplication.context));
                        break;
                    case 2:

                        break;

                }
            }
        });

    }

    @Override
    public void initListener() {
        ivBack.setOnClickListener(this);
        ivForward.setOnClickListener(this);
        ivCollect.setOnClickListener(this);
        ivInternalSearch.setOnClickListener(this);
        ivRefresh.setOnClickListener(this);
        ivWindows.setOnClickListener(this);
        ivGo.setOnClickListener(this);

        ivWindowAdd.setOnClickListener(this);
        ivWindowDelete.setOnClickListener(this);
        ivWindowBack.setOnClickListener(this);
        //

        //监听输入框焦点
        etUrl.setOnFocusChangeListener(this);
        etUrl.setOnClickListener(this);
        //监听输入框内容变化
        etUrl.addTextChangedListener(new EditTextChangeListener(etUrl) {
            @Override
            public void afterTextChanged(Editable s) {
                String content = getContent(etUrl);
                LogUtils.e(content);
                browserPresenter.search();
            }
        });
        //监听条目点击事件
        lvKeyWords.setOnItemClickListener(this);
        //
//        webView.setOnClickListener(this);
        rlWebGroup.setOnClickListener(this);
    }


    @Override
    public int getLayout() {
        return R.layout.activity_browser;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_internal_search_browser:

                break;
            case R.id.iv_windows_add:
                webViewCount++;//集合中webView的数量增加
                LogUtils.e("iv_windows_add");
                WebView webView = newTab();
                loadTab(webView, HOME_URL);

                switchover1();
                rvWindows.setVisibility(View.GONE);

                quickAdapter.notifyDataSetChanged();
                LogUtils.e("windows:" + windows.size());
                //
                break;
            case R.id.iv_windows_back:
                switchover1();
                rvWindows.setVisibility(View.GONE);
                break;
            case R.id.iv_windows_delete:

                break;

            /*case R.id.iv_menu_browser:

                break;*/
            case R.id.iv_refresh_browser://refresh view
                this.mCurrentView.reload();
                break;
            case R.id.iv_back_browser:
                if (isVISIBLE(lvBookMarks, LISTVIEW)) {
                    lvBookMarks.setVisibility(View.GONE);
                }
                if (this.mCurrentView.canGoBack()) {
                    this.mCurrentView.goBack();
                }
                break;
            case R.id.iv_collect_browser://collect url
                addBookMark();
                break;
            case R.id.iv_forward_browser:
                this.mCurrentView.goForward();
                break;
            case R.id.iv_windows_browser://windows
                switchover2();
                rvWindows.setVisibility(View.VISIBLE);
//                llTools.setVisibility(View.GONE);
//                llWindowsOperater.setVisibility(View.VISIBLE);

                //
                bitmaps.clear();
                for (WebView wv : windows) {
                    drawingCache = wv.getDrawingCache();
                    windowBean = new WindowBean(wv.getTitle(), drawingCache);
                    bitmaps.add(windowBean);
                }
                //设置布局管理器
                LinearLayoutManager manager = new LinearLayoutManager(this);
                manager.setOrientation(LinearLayoutManager.VERTICAL);//横向

                rvWindows.setLayoutManager(manager);
                rvWindows.addItemDecoration(new WindowDecoration(0, 5, 5, 0));
                LogUtils.e("bitmaps:" + bitmaps.size());
                //设置Adapter
                quickAdapter = new QuickAdapter(bitmaps);
                //条目点击事件
                quickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        LogUtils.e("6666666666");
                        //重新加载被点击的webView
                        switchover1();
                        rvWindows.setVisibility(View.GONE);
                        //移除当前容器中的webView，添加新的webView

                        WebView webView = windows.get(position);
                        showTab(webView);
                    }
                });
                rvWindows.setAdapter(quickAdapter);
                quickAdapter.notifyDataSetChanged();
                break;

            case R.id.iv_go_browser:

                break;
            case R.id.et_url_browser:
                //获取焦点
                getFocus(etUrl);
                // 弹出软键盘
                openKeyboard(etUrl, this);
                break;

            case R.id.rl_web_group:
                LogUtils.e("rl_web_group被点击了");
                closeKeyboard(etUrl, this);
                break;

            case R.id.boom:
                LogUtils.e("boom被点击了");
                break;


        }
    }

    private void addWebView(WebView webView, RelativeLayout relativeLayout) {
        layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        relativeLayout.addView(webView, layoutParams);
    }

    private void switchover1() {
        llTools.setVisibility(View.VISIBLE);
        llWindowsOperater.setVisibility(View.GONE);
    }

    private void switchover2() {
        llTools.setVisibility(View.GONE);
        llWindowsOperater.setVisibility(View.VISIBLE);
    }

    private void addBookMark() {
        String url = mCurrentView.getUrl();
        String title = mCurrentView.getTitle();
        LogUtils.e("BookMark:" + url);
        ToastUtil.showShort(BrowserApplication.context, "已添加书签");
        realm.beginTransaction();//开启事务
        BookMarkBean bookMark = realm.createObject(BookMarkBean.class);
        bookMark.setUrl(url);
        bookMark.setTitle(title);
        realm.commitTransaction();//提交事务
    }


    /**
     * 关闭软键盘
     */
    public void closeKeyboard(EditText editText, Context context) {
        InputMethodManager imm = (InputMethodManager) getSystemService(context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    @Override
    public void inputContent(EditText editText) {
        //获取内容
//        String content = editText.getText().toString().trim();

    }

    @Override
    public String getContent(EditText editText) {
        //获取内容
        String content = editText.getText().toString().trim();
        return content;
    }

    @Override
    public void loadHomePage() {
        WebView homeWebview = newTab();
        loadTab(homeWebview, HOME_URL);
    }

    @Override
    public void webViewOperate(String url, WebView wv) {
        //
        wv.setBackgroundColor(Color.parseColor("#FFFFFF"));
        //保存到内存

        wv.setWebViewClient(new BrowserClient(BrowserApplication.realm));
        wv.setWebChromeClient(new BrowserChromeClient(mpb, BrowserApplication.realm));

        //允许缓存
        wv.setDrawingCacheEnabled(true);

        /**
         * WebSettings
         */
        WebSettings settings = wv.getSettings();
        //支持js操作
        settings.setJavaScriptEnabled(true);
        //多窗口
        settings.supportMultipleWindows();
        //使用默认的缓冲模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //将图片调整到适合webview的大小
        settings.setUseWideViewPort(false);
        //支持JS
        settings.setJavaScriptEnabled(true);
        //设置编码格式
        settings.setDefaultTextEncodingName("UTF-8");

        wv.loadUrl(url);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void getFocus(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
    }

    @Override
    public void clearFocus(EditText editText) {
        editText.clearFocus();
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
    }

    /**
     * 弹出软键盘
     */
    public void openKeyboard(EditText editText, Context context) {
        // 获取焦点
        getFocus(editText);
        // 弹出软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, 0);
    }

    public EditText getEditText() {
        return etUrl;
    }

    //接收EventBus发送的事件
    @Subscribe
    public void onMessageEvent(KeyWordEvent event) {
        //获取提示keyword
        String result = event.getContent();
        result = result.substring(17, result.length() - 2);
        LogUtils.e(result);
//        解析
        Gson gson = new Gson();
        KeyWordBean keyWordBean = gson.fromJson(result, KeyWordBean.class);
        keyWordList = keyWordBean.getS();
        showKeyWords();
    }

    private void showKeyWords() {
        lvKeyWords.setVisibility(View.VISIBLE);
        //设置适配器
        lvKeyWords.setAdapter(new KeyWordAdapter(keyWordList, this));
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        lvKeyWords.setVisibility(View.GONE);
        String keyWord = keyWordList.get(position);
        //https://m.baidu.com/s?from=8415170&word=666
        String url = Contants.BAIDU_SEARCH + keyWord;
//        loadPage(url);
        WebView webView = new WebView(this);
        webViewOperate(url, webView);
    }


    private EditText etUrl;
    private ImageView ivInternalSearch;
    private ImageView ivGo;

    private ImageView ivRefresh;
    private ImageView ivBack;
    private ImageView ivCollect;
    private TextView ivWindows;
    private ImageView ivForward;
    private ListView lvBookMarks;
    private ListView lvHistory;
    private RecyclerView rvWindows;
    private WindowBean windowBean;
    private ImageView ivWindowAdd;
    private ImageView ivWindowBack;
    private ImageView ivWindowDelete;
    private LinearLayout llTitle;
    private LinearLayout llTools;


    @Override
    public void initView() {
        etUrl = (EditText) findViewById(R.id.et_url_browser);
        ivInternalSearch = (ImageView) findViewById(R.id.iv_internal_search_browser);
        ivGo = (ImageView) findViewById(R.id.iv_go_browser);
//        webView = (WebView) findViewById(R.id.wv_browser);
        ivRefresh = (ImageView) findViewById(R.id.iv_refresh_browser);
        ivBack = (ImageView) findViewById(R.id.iv_back_browser);
        ivCollect = (ImageView) findViewById(R.id.iv_collect_browser);
        ivForward = (ImageView) findViewById(R.id.iv_forward_browser);
        ivWindows = (TextView) findViewById(R.id.iv_windows_browser);
        lvKeyWords = (ListView) findViewById(R.id.lv_keywords_browser);
        lvBookMarks = (ListView) findViewById(R.id.lv_bookmark_browser);
        lvHistory = (ListView) findViewById(R.id.lv_history_browser);
        llTitle = (LinearLayout) findViewById(R.id.ll_title_browser);
        llTools = (LinearLayout) findViewById(R.id.ll_tools_browser);
        mpb = (MagicProgressBar) findViewById(R.id.mpb_browser);
        boomMenuButton = (BoomMenuButton) findViewById(R.id.boom);
        rvWindows = (RecyclerView) findViewById(R.id.rv_browser);
        ivWindowAdd = (ImageView) findViewById(R.id.iv_windows_add);
        ivWindowBack = (ImageView) findViewById(R.id.iv_windows_back);
        ivWindowDelete = (ImageView) findViewById(R.id.iv_windows_delete);
        rlWebGroup = (RelativeLayout) findViewById(R.id.rl_web_group);
        llWindowsOperater = (LinearLayout) findViewById(R.id.ll_windows_operate);
    }

    private WebView newTab() {
        WebView webView = new WebView(this);
        windows.add(webView);
        return webView;
    }

    private WebView mCurrentView;

    private void showTab(WebView webView) {
        if (mCurrentView == webView) {
            return;
        }
        rlWebGroup.removeView(mCurrentView);
        addWebView(webView, rlWebGroup);
        mCurrentView = webView;
    }

    private void loadTab(WebView webView, String url) {
        if (mCurrentView != null){
            rlWebGroup.removeView(mCurrentView);
        }
        addWebView(webView, rlWebGroup);
        mCurrentView = webView;
        webViewOperate(HOME_URL, webView);
    }

}
